package pt.minha.disk.simulation;

public class Request {
	
	private long timeStamp;
	private final RequestType reqType;
	private int length;
	private int idFile;
	private Storage st;
	private long cost;
	private boolean done;

	public Request(RequestType requestType, int length, int idFile, Storage st) {
		this.done = false;
		this.st = st;
		this.timeStamp = 0;
		this.cost = 0;
		this.reqType = requestType;
		this.length = length;
		this.idFile = idFile;
	}

	/**
	 * @return the timeStamp
	 */
	public long getTimeStamp() {
		return timeStamp;
	}

	/**
	 * @return the reqType
	 */
	public RequestType getReqType() {
		return reqType;
	}

	/**
	 * @return the length
	 */
	public int getLength() {
		return length;
	}

	/**
	 * @return the idFile
	 */
	public int getIdFile() {
		return idFile;
	}
	
	/**
	 * @return the done
	 */
	public boolean isDone() {
		return done;
	}

	/**
	 * @param timeStamp the timeStamp to set
	 */
	public void setTimeStamp(long timeStamp) {
		this.timeStamp = timeStamp;
	}
	
	/**
	 * Function for subtract the length
	 * This function is just for bucket control
	 * @return the quantity of subtraction
	 */
	public int process(int sLength) {
		this.length -= sLength;
		if(this.length < 0) {
			this.done = true;
			return sLength + this.length;
		}
		return sLength;
	}

	/***
	 * Function for added the request to be handle by disk
	 * @return
	 */
	public synchronized long execute(){
		this.st.addRequest(this);
		try {
			this.wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this.cost;
	}
	
	/***
	 * Function responsible for return and calculate the request time to handle
	 * @param cost - time to handle
	 */
	public synchronized void done(long cost) {
		if(this.timeStamp == 0) this.cost = cost;
		else{
			this.cost = System.nanoTime() - this.timeStamp + cost;
		}
		
		this.notify();
	}

}
